package is202.hrms.ejb;

import is202.hrms.entity.Progress;
import is202.hrms.entity.Usere;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;



/**
 * This ejb handles database operations for Progress objects.
 * It does not have any fields (except for the entity manager which
 * is handled by the container), which means it can't keep state, and
 * is annotated with Stateless to mark it as a stateless session bean.
 * A stateless bean can be shared by several users, so it is efficient
 * with regards to resource usage.
 *
 * @author evenal
 */
@Stateless
public class ProgressEJB extends AbstractFacade<Progress> {
    /**
     * The PersistenceContext annotation is a request to  the
     * container (GlassFish) to create or find an EntityManager and
     * store it in the field em. We get the EntityManager object we need,
     * without having to write the code to create it. This is called
     * userendency injection.
     */
    @PersistenceContext
    private EntityManager em;
    
    @EJB UserEJB userEjb;

    /** This method is used in the methods inherited from AbstractFacade
     * to access the EntityManager */
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ProgressEJB() {
        super(Progress.class);
    }

    /** Method returns the first userartment it finds. It is used by the
     * employee page, to make sure that every employee belongs to a userartment
     */
    public Progress getDefaultProgress() {
        List<Progress> userList = findAll();
        if (userList != null && userList.size() > 0) {
            return userList.get(0);
        } else {
            throw new IllegalStateException("Ingen brukere eksisterer.");
        }
    }

    /** A wrapper for the find() method in AbstractFacade. It allows us
     * to pass the primary key as the primitive type long, rather than
     * as the wrapper type Long. It also forces loading of the userartment's
     * employees */
    public Progress find(long userId) {
        Progress user = super.find(userId);
        return user;
    }

    @Override
    public void delete(Progress user) {
        user = em.merge(user);
        super.delete(user);
        
    }
    
    @Override
    public Progress insert(Progress progress) {
        Usere user = userEjb.find(progress.getBruker().getId());
        progress = super.insert(progress);
        user.getProgress().add(progress);
        progress.setBruker(user);
        return progress;
    }

}
